package com.ksyzt.ksite2.server.servlet;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;
import gwtupload.shared.UConsts;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.ksyzt.gwt.server.common.Util;
import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IATTACHMENTDAO;
import com.ksyzt.ksite2.server.database.dao.impl.ATTACHMENTDAOImpl;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;

/**
 * 文件上传接受端
 *
 * @author 张建设
 *
 */
public class UploadServlet extends UploadAction {

	private static final long serialVersionUID = 1L;
	private static final String UPLOAD_PATH = "upload";

	/*
	 * (non-Javadoc)
	 *
	 * @see gwtupload.server.UploadServlet#checkRequest(javax.servlet.http.
	 * HttpServletRequest)
	 */
	@Override
	public void checkRequest(HttpServletRequest request) {
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		super.checkRequest(request);
	}

	/**
	 * Override executeAction to save the received files in a custom place and
	 * delete this items from session.
	 */
	@Override
	public String executeAction(HttpServletRequest request,
			List<FileItem> sessionFiles) throws UploadActionException {
		String response = "";
		int cont = 0;
		for (FileItem item : sessionFiles) {
			if (false == item.isFormField()) {
				cont++;
				try {
					// / Create a new file based on the remote file name in the
					// client
					// String saveName =
					// item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+",
					// "_");
					// File file =new File("/tmp/" + saveName);

					// / Create a temporary file placed in /tmp (only works in
					// unix)
					// File file = File.createTempFile("upload-", ".bin", new
					// File("/tmp"));

					// / Create a temporary file placed in the default system
					// temp folder

					// we save the uploaed file to upload directory
					String rootpath = request.getRealPath("/");
					File dir = new File(rootpath);
					if (!dir.exists()) {
						dir.mkdirs();
					}

					String fname = item.getName();
					String filename_local = "";
					String filename_org = "";

					int pos = fname.lastIndexOf(".");

					int posSep = fname.lastIndexOf(File.separatorChar);

					if (pos >= 0) {
						filename_local = UPLOAD_PATH + File.separator
								+ Util.randomString(10) + fname.substring(pos);
					} else {
						filename_local = UPLOAD_PATH + File.separator
								+ Util.randomString(10);
					}

					if (posSep >= 0) {
						filename_org = fname.substring(posSep + 1);
					} else {
						filename_org = fname;
					}

					File file = new File(rootpath + "/" + filename_local);
					item.write(file);

					// / Send a customized message to the client.
					response += "File saved as " + file.getAbsolutePath();

					String fieldname = item.getFieldName();
					String[] parts = fieldname.split("-");
					String nid = parts[0];

					IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(
							Application.getConnection());
					ATTACHMENTObj att = new ATTACHMENTObj();
					att.setCDATE(Util.getCurrentSQLTimestamp());
					att.setDCOUNT(0);
					att.setTAG(fieldname);
					att.setFILEPATH(filename_local);
					att.setNID(nid);
					att.setFTYPE(item.getContentType());
					att.setTITLE(filename_org);
					dao.insertObject(att);

				} catch (Exception e) {
					throw new UploadActionException(e);
				}
			}
		}

		// / Remove files from session because we have a copy of them
		removeSessionFileItems(request);

		// / Send your customized message to the client.
		return response;
	}

	/**
	 * Get the content of an uploaded file.
	 */
	@Override
	public void getUploadedFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String fieldName = request.getParameter(UConsts.PARAM_SHOW);
		ATTACHMENTObj att = getAttatchement(fieldName);
		String rootpath = request.getRealPath("/");
		File f = new File(rootpath + att.getFILEPATH());
		if (f.exists()) {
			response.setContentType(att.getFTYPE());
			FileInputStream is = new FileInputStream(f);
			copyFromInputStreamToOutputStream(is, response.getOutputStream());
		} else {
			renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
		}
	}

	public ATTACHMENTObj getAttatchement(String fieldname) {
		IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(Application.getConnection());
		try {
			return dao.findByTAG(fieldname);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Remove a file when the user sends a delete request.
	 */
	@Override
	public void removeItem(HttpServletRequest request, String fieldName)
			throws UploadActionException {
		ATTACHMENTObj att = getAttatchement(fieldName);

		if (att != null) {
			IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(
					Application.getConnection());
			String rootpath = request.getRealPath("/");
			File f = new File(rootpath + att.getFILEPATH());
			if (f.exists()) {
				f.delete();
			}

			try {
				dao.deleteByPK(att.getAID());
			} catch (SQLException e) {
				e.printStackTrace();
				throw new UploadActionException("不能删除数据库信息");
			}

		}

	}

}
